package com.flca.frw.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

public class ReadCsvHelper {

	private static final String DELIM1 = ";";
	private static final String DELIM2 = ",";
	
	public static String[][] readCvsFile(Class<?> aRefclass, String aResourceName)
		throws IOException 
	{
		List<String> lines = readFromResource(aRefclass, aResourceName);
		
		String delim = DELIM1;
		
		String line1 = lines.get(0);
		if (line1.indexOf(DELIM2) > 0) {
			delim = DELIM2;
		} else {
			delim = DELIM1;
		}
		
		String headers[] = StringUtils.split(line1, delim);
		
		String result[][] = new String[lines.size()][headers.length];
		
		int lineNr = 0;
		for (String line : lines) {
			if (line.trim().length() > 0) {
				String items[] = StringUtils.split(line, delim);
				int i = 0;
				for (String s : items) {
					if (i < result[0].length) {
						result[lineNr][i] = s.trim();
					}
					i++;
				}
				lineNr++;
			}
		}
		
		return result;
	}
	
	private static List<String> readFromResource(Class<?> aRefclass, String aResourceName)
			throws IOException 
	{
		List<String> result = new ArrayList<String>();
		
		InputStream is = aRefclass.getResourceAsStream(aResourceName);

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String line = reader.readLine();
		while (line != null) {
			result.add(line);
			line = reader.readLine();
		}
		
		reader.close();
		is.close();
		return result;
		
	}
}